import numpy as np
import joblib
from skimage.io import imread
from skimage.transform import resize
from skimage.feature import hog
import matplotlib.pyplot as plt

# 加载训练好的模型
knn = joblib.load("knn_model.pkl")

# 读取测试图像（示例路径）
test_img_path = r"F:\人工智能教材编写\traffic_sign\test\00_00.png"  # 替换为实际路径
image = imread(test_img_path)

# 预处理流程（与训练完全一致）
gray_image = imread(test_img_path, as_gray=True)
resized_image = resize(gray_image, (64, 64))

# HOG特征提取
hog_features = hog(resized_image,
                   orientations=9,
                   pixels_per_cell=(8, 8),
                   cells_per_block=(2, 2),
                   visualize=False)

# 预测并获取结果
predicted_label = knn.predict([hog_features])[0]
print(predicted_label)

# 读取类别名称
with open(r"F:\人工智能教材编写\traffic_sign\classes.txt", "r", encoding="utf-8") as f:
    class_names = [line.strip() for line in f.readlines()]
predicted_name = class_names[predicted_label]
print(predicted_name)

plt.imshow(image)
plt.show()
